<template>
  <div class="product-list-container">
    <a-form layout="inline">
      <a-form-item label="产品名称">
        <a-input v-model="searchForm.name" placeholder="产品名称" allowClear />
      </a-form-item>
      <a-form-item label="渠道">
        <a-select 
          v-model="searchForm.platform" 
          placeholder="请选择渠道" 
          allowClear
          style="width: 120px"
        >
          <a-select-option value="">全部</a-select-option>
          <a-select-option value="招商银行">招商银行</a-select-option>
          <a-select-option value="建设银行">建设银行</a-select-option>
          <a-select-option value="平安银行">平安银行</a-select-option>
          <a-select-option value="北京银行">北京银行</a-select-option>
          <a-select-option value="交通银行">交通银行</a-select-option>
          <a-select-option value="网商银行">网商银行</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="渠道">
        <a-select 
          v-model="searchForm.productType" 
          placeholder="请选择创建类型" 
          allowClear
          style="width: 120px"
        >
          <a-select-option value="system">系统</a-select-option>
          <a-select-option value="user">用户</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="onSearch">搜索</a-button>
        <a-button style="margin-left: 20px;" type="primary" @click="onClearSearch">清空</a-button>
      </a-form-item>
    </a-form>
    <a-button style="margin-top:8px;" type="primary" @click="openProductModal('add')">新增产品</a-button>
    <div class="table-container">
      <a-table
      :columns="columns"
      :dataSource="products"
      :pagination="false"
      :scroll="{ y: 560 }"
      rowKey="_id"
      style="margin-top:16px;"
    >
      <span slot="action" slot-scope="text, record">
        <a @click="openNetValueModal(record)">净值列表</a>
        <a-divider type="vertical" />
        <a @click="openProductModal('edit', record)">
          <a-icon type="edit" />
          编辑</a>
        <a-divider type="vertical" />
        <a-popconfirm
          title="确定要删除这个产品吗？"
          ok-text="确定"
          cancel-text="取消"
          @confirm="deleteProduct(record)"
        >
          <a style="color: #ff4d4f">删除</a>
        </a-popconfirm>
      </span>
    </a-table>
    <a-pagination
      :current="pagination.current"
      :pageSize="pagination.pageSize"
      :total="pagination.total"
      :showTotal="pagination.showTotal"
      :showQuickJumper="pagination.showQuickJumper"
      :showSizeChanger="pagination.showSizeChanger"
      style="margin-top: 16px; text-align: right;"
      @change="onPageChange"
      @showSizeChange="onPageSizeChange"
    />
    </div>
    <a-modal
      :title="productModalType === 'add' ? '新增产品' : '编辑产品'"
      v-model="productModalVisible"
      @ok="saveProduct"
      :destroyOnClose="true"
      :width="1000"
    >
      <ProductForm ref="productForm" :initialData="editingProduct" />
    </a-modal>

    <!-- 产品净值弹框 -->
    <a-modal
      title="产品净值"
      v-model="netValueModalVisible"
      :footer="null"
      :destroyOnClose="true"
      :width="1000"
    >
      <ProductNavs :product-id="selectedProductId" @click="handleClick" />
    </a-modal>
  </div>
</template>

<script>
import { fetchProducts, deleteProduct, addProduct, updateProduct, fetchProductDetail } from '@/api/product';
import ProductForm from './ProductForm.vue';
import ProductNavs from './ProductNavs.vue';
import moment from 'moment';

export default {
  components: { ProductForm, ProductNavs },
  data() {
    return {
      searchForm: {
        name: '',
        platform: '',
        productType: 'system'
      },
      products: [],
      tableHeight: 300,
      pagination: {
        current: 1,
        pageSize: 20,
        total: 0,
        showTotal: total => `共 ${total} 条`,
        showQuickJumper: true,
        showSizeChanger: true
      },
      columns: [
        { title: '产品名称', dataIndex: 'name', key: 'name' },
        { title: '渠道', dataIndex: 'platform', key: 'platform' },
        { title: '发行机构', dataIndex: 'issuer', key: 'issuer' },
        { title: '创建类型', dataIndex: 'productType', key: 'productType', customRender: t => t ==='system' ? '系统' : '用户' },
        { title: '近1个月年化', dataIndex: 'rate1m', key: 'rate1m', customRender: t => t },
        { title: '最新净值日期', dataIndex: 'lastNavUpdateDate', key: 'lastNavUpdateDate' },
        { title: '确认期', dataIndex: 'confirmDays', key: 'confirmDays', customRender: t => 'T + ' + t },
        { title: '是否生效', dataIndex: 'isActive', key: 'isActive', customRender: t => t ? '是' : '否' },
        { title: '操作', key: 'action', scopedSlots: { customRender: 'action' } }
      ],
      productModalVisible: false,
      productModalType: 'add',
      editingProduct: {},
      netValueModalVisible: false, // 净值列表弹框显示状态
      selectedProductId: null // 当前选中的产品ID
    };
  },
  methods: {
    handleClick() {
      this.fetchData(this.pagination.current, this.pagination.pageSize);
    },
    async fetchData(page = 1, pageSize = 20) {
      const params = {
        page,
        pageSize,
        keyword: this.searchForm.name,
        platform: this.searchForm.platform,
        productType: this.searchForm.productType,
        scope: 'all'
      };
      const res = await fetchProducts(params);
      console.log('res :>> ', res);
      this.products = res.list;
      this.pagination = {
        ...this.pagination,
        current: Number(res.page) || 1,
        pageSize: Number(res.pageSize) || 10,
        total: Number(res.total) || 0
      };
    },
    onSearch() {
      this.fetchData(1);
    },
    onClearSearch() {
      this.searchForm = {
        name: '',
        platform: '',
        productType: ''
      }
      this.fetchData(1);
    },
    onPageChange(page, pageSize) {
      this.fetchData(page, pageSize);
    },
    onPageSizeChange(current, size) {
      this.fetchData(1, size);
    },
    openProductModal(type, record) {
      this.productModalType = type;
      this.productModalVisible = true;
      if (type === 'edit' && record) {
        fetchProductDetail(record._id).then(res => {
          this.editingProduct = res || {};
          // 处理日期字段
          if (this.editingProduct.date) {
            this.editingProduct.date = moment(this.editingProduct.date);
          }
          this.$nextTick(() => {
            if (this.$refs.productForm) {
              console.log('设置表单值:', this.editingProduct);
              this.$refs.productForm.setFieldsValue(this.editingProduct);
            }
          });
        }).catch(error => {
          console.error('获取产品详情失败:', error);
          this.$message.error('获取产品详情失败');
        });
      } else {
        this.editingProduct = {};
        this.$nextTick(() => {
          if (this.$refs.productForm) {
            this.$refs.productForm.resetFields();
          }
        });
      }
    },
    saveProduct() {
      this.$refs.productForm.validate((err, values) => {
        if (err) {
          console.error('表单验证失败:', err);
          return;
        }
        
        // 确保必填字段存在且不为空
        if (!values.name || !values.name.trim()) {
          this.$message.error('产品名称不能为空');
          return;
        }
        if (!values.platform || !values.platform.trim()) {
          this.$message.error('渠道不能为空');
          return;
        }
        values.productType = 'system';
        // 发送请求
        const saveRequest = this.productModalType === 'add' 
          ? addProduct(values)
          : updateProduct(this.editingProduct._id, values);

        saveRequest
          .then(() => {
            this.productModalVisible = false;
            this.fetchData(this.pagination.current, this.pagination.pageSize);
            this.$message.success('保存成功');
          })
          .catch(error => {
            console.error('保存失败:', error);
          });
      });
    },
    async deleteProduct(record) {
      try {
        await deleteProduct(record._id);
        this.$message.success('删除成功');
        this.fetchData(this.pagination.current, this.pagination.pageSize);
      } catch (error) {
        console.error('删除失败:', error);
      }
    },
    calculateTableHeight() {
      const windowHeight = window.innerHeight;
      const offset = 280; // 预留空间给其他元素（头部、搜索栏、分页等）
      this.tableHeight = windowHeight - offset;
    },
    handleResize() {
      this.calculateTableHeight();
    },
    openNetValueModal(record) {
      this.selectedProductId = record._id;
      this.netValueModalVisible = true;
    }
  },
  mounted() {
    this.fetchData();
    this.calculateTableHeight();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  }
};
</script>

<style lang="less" scoped>
.product-list-container {
  height: 100%;
  padding: 24px;
  background-color: #f0f2f5;
}

.table-container {
  margin-top: 16px;
  padding: 24px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}
</style> 